package com.example.controller;

import com.example.pojo.Session;
import com.example.service.SessionService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@RequestMapping("/ai")
@AllArgsConstructor
public class ChatController {
    private final ChatClient deepseekChatClient;
    private final ChatClient openaiChatClient;
    private final SessionService sessionService;
    private final ChatMemory chatMemory;
    
    @GetMapping("/test")
    public String test(String prompt) {
        return deepseekChatClient
                .prompt()
                .user(prompt)
                .call()
                .content();
    }

    @PostMapping(value = "/chat", produces = "text/html;charset=utf-8")
    public Flux<String> chat(String prompt, String chatId) {
        try {
            //预处理
            preOperation(chatId);
            //流式输出
            return openaiChatClient
                    .prompt()
                    .user(prompt)
                    .advisors(a -> a.param(ChatMemory.CONVERSATION_ID, chatId))
                    .stream()
                    .content();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private void preOperation(String chatId) {
        Session session = sessionService.getSessionById(chatId);
        if (ObjectUtils.isEmpty(session)) {
            session = new Session();
            session.setSessionId(chatId);
            sessionService.addSession(session);
        }
    }

    @PostMapping("/addSession")
    public Session addSession(@RequestBody Session session){
        return sessionService.addSession(session);
    }

}
